package com.google.jguery.client.index;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.google.jguery.client.analyzer.Analyzer;
import com.google.jguery.client.common.FieldText;
import com.google.jguery.client.common.TermPostings;

public class Table {
	
	//whoosh's implementation is having keys in order, while I am just using Map
	//needs to think about whether I want to use TreeMap keeping keys in order or not
	Map<FieldText, TermPostings> table;
	boolean hasPostings = false;

	public Table() {
		table = new HashMap<FieldText, TermPostings>();
		hasPostings = true;
	}
	
	public Table(Map<FieldText, TermPostings> table) {
		this.table = table;
		hasPostings = true;
	}
	
	public void clear() {
		table.clear();
	}
	
	//not sure if this is necessary, it is more than add, it's "put"
	public void addRow(FieldText key, TermPostings postings) {
		table.put(key, postings);
	}
	
	public boolean contains(FieldText key) {
		return table.containsKey(key);
	}

	
	public Set<FieldText> getKeys() {
		return table.keySet();
	}
	
	public int getPostingsDocCount(FieldText key) {
		return table.get(key).getDocCount();
	}
	
	public int getPostingsTermCount(FieldText key) {
		return table.get(key).getTermCount();
	}
	
	public TermPostings getPostings(FieldText key) {
		return table.get(key);
	}

	public void update(int docId, String text, String field, Analyzer analyzer) {
		String [] words = analyzer.parse(text);
		int pos = 0;
		for (String word : words) {
			FieldText key = new FieldText(field, word);
			if (contains(key)) {
				TermPostings termPostings = getPostings(key);
				termPostings.add(docId, pos);
			} else {
				TermPostings termPostings = new TermPostings();
				termPostings.add(docId, pos);
				addRow(key, termPostings);
			}
			pos++;
		}
	}
	
	public void update(int docNum, String text, Analyzer analyzer) {
		update(docNum, text, "body", analyzer);
	}
	
	public String toString() {
		if (table == null) return "[]";
		StringBuilder sb = new StringBuilder();
		sb.append("[");
		for (FieldText key : table.keySet()) {
			sb.append(key);
			sb.append(table.get(key));
		}
		sb.append("]");
		return sb.toString();
	}
}